"use strict";
var __createBinding = this && this.__createBinding || (Object.create ? function (e, t, s, i) {
    void 0 === i && (i = s);
    var o = Object.getOwnPropertyDescriptor(t, s);
    o && !("get" in o ? !t.__esModule : o.writable || o.configurable) || (o = {
        enumerable: !0, get: function () {
            return t[s]
        }
    }), Object.defineProperty(e, i, o)
} : function (e, t, s, i) {
    void 0 === i && (i = s), e[i] = t[s]
}), __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (e, t) {
    Object.defineProperty(e, "default", { enumerable: !0, value: t })
} : function (e, t) {
    e.default = t
}), __importStar = this && this.__importStar || function (e) {
    if (e && e.__esModule) {
        return e;
    }
    var t = {};
    if (null != e) {
        for (var s in e) {
            "default" !== s && Object.prototype.hasOwnProperty.call(e, s) &&
            __createBinding(t, e, s);
        }
    }
    return __setModuleDefault(t, e), t
}, __importDefault = this && this.__importDefault || function (e) {
    return e && e.__esModule ? e : { default: e }
};
Object.defineProperty(exports, "__esModule", { value: !0 }), exports.ProcessProfile = void 0;
const path_1 = __importDefault(require("path")), wdk_1 = require("@baize/wdk"), hvigor_1 = require("@ohos/hvigor"),
    fs = __importStar(require("fs-extra")), fs_extra_1 = __importDefault(require("fs-extra")),
    common_const_js_1 = require("../const/common-const.js"),
    virtual_machine_enum_js_1 = require("../enum/virtual-machine-enum.js"),
    inject_util_js_1 = require("../utils/inject-util.js"),
    integrated_hsp_utils_js_1 = require("../utils/integrated-hsp-utils.js"),
    task_names_js_1 = require("./common/task-names.js"), merge_profile_js_1 = require("./merge-profile.js"),
    ohos_hap_task_js_1 = require("./task/ohos-hap-task.js");
var Task = task_names_js_1.TaskNames.Task;
const json_util_js_1 = require("../utils/json-util.js"), ohmurl_utils_js_1 = require("../utils/ohmurl-utils.js"),
    ohos_logger_js_1 = require("../utils/log/ohos-logger.js"), INPUT_KEY = {
        arkEnable: "arkEnable",
        compileMode: "compileMode",
        deviceTypes: "deviceTypes",
        dependency: "dependency",
        harExcludeHSPDependencies: "harExcludeHSPDependencies"
    }, _log = ohos_logger_js_1.OhosLogger.getLogger("hvigor-process-profile");

class ProcessProfile extends ohos_hap_task_js_1.OhosHapTask {
    constructor(e) {
        super(e, Task.PROCESS_PROFILE), this._dependencies = [], this.harExtensionAbilities = [], this._arkEnable =
            this.service.isArkModule(), this._moduleTargetData = this.targetService.getTargetData(), this._deviceTypes =
            this._moduleTargetData.getTargetDeviceType(), this._pathInfo =
            this._moduleTargetData.getPathInfo(), this._intermediatesMergeProfile =
            this._pathInfo.getIntermediatesMergeProfile(), this._processedModuleJson =
            this._pathInfo.getIntermediatesProcessProfile(), this.mergeHspLibs()
            .forEach(e => this._dependencies.push(e))
    }

    initTaskDepends() {
        this.declareDepends(merge_profile_js_1.MergeProfile.name)
    }

    shouldCollectDependenciesAbilities() {
        return !inject_util_js_1.InjectUtil.isLocalTest() &&
            (this.moduleModel.isHapModule() || this.moduleModel.isHspModule() ||
            inject_util_js_1.InjectUtil.isOhosTest() || inject_util_js_1.InjectUtil.isPreviewProcess())
    }

    async beforeAlwaysAction() {
        await super.beforeAlwaysAction(), this.shouldCollectDependenciesAbilities() && (this.harExtensionAbilities =
            this.collectHarAbilities(common_const_js_1.AbilityConst.EXTENSION_ABILITY)), this.validateExtensionAbilities()
    }

    validateExtensionAbilities() {
        const e = (0, json_util_js_1.getJson5Obj)(this._intermediatesMergeProfile).module.extensionAbilities || [];
        if (e.push(...this.harExtensionAbilities), !e.length) {
            return;
        }
        const t = this.findDuplicatedAbilityNames(e);
        t.length &&
        _log.warn(`Duplicate 'Extension-Abilities' object names detected: ${JSON.stringify(t)}. \n    Make sure the names are unique across the current module and the modules on which it depends.`)
    }

    doTaskAction() {
        const e = (0, json_util_js_1.getJson5Obj)(this._intermediatesMergeProfile),
            t = this.projectModel.getCompatibleApiMetaByProduct(this.targetData.getProduct().name).version;
        e.module.virtualMachine = this._arkEnable ?
            `${virtual_machine_enum_js_1.VirtualMachine.ARK}${this.sdkInfo.getArkVersion(t,
                this.compatibleSdkVersionStage)}` :
        virtual_machine_enum_js_1.VirtualMachine.DEFAULT, e.module.compileMode =
            this.targetCompileMode, e.module.deviceTypes = this._deviceTypes, this.addModuleDependencies(e), e &&
            (this.processModuleAndAbility(e), this.processExtensionAbility(e), this.processTestRunner(e));
        const s = this.pathInfo.getIntermediatesArkModuleJsonPath();
        fs.ensureFileSync(s), fs.writeFileSync(s,
            JSON.stringify(e)), this.processDependencyHarAbility(e), fs.outputJSONSync(this._processedModuleJson, e,
            { spaces: "\t" })
    }

    declareInputs() {
        const e = new Map;
        return e.set(INPUT_KEY.arkEnable, this._arkEnable), e.set(INPUT_KEY.compileMode,
            this.targetCompileMode), e.set(INPUT_KEY.deviceTypes, this._deviceTypes), e.set(INPUT_KEY.dependency,
            JSON.stringify(this._dependencies)), e.set(INPUT_KEY.harExcludeHSPDependencies,
            hvigor_1.hvigorCore.getParameter()
                .getProperty(common_const_js_1.CommonConst.HAR_EXCLUDE_HSP_DEPENDENCIES)), e.set("compatibleSdkVersionStage",
            this.compatibleSdkVersionStage || ""), e
    }

    declareInputFiles() {
        return (new hvigor_1.FileSet).addEntry(this._intermediatesMergeProfile)
    }

    declareOutputFiles() {
        return (new hvigor_1.FileSet).addEntry(this._processedModuleJson)
    }

    mergeHspLibs() {
        const e = this.service.getHspDependencyPaths(), t = this.service.getHspModuleDependencyPathsWithOutDynamic(),
            { versionCode:s } = (0, integrated_hsp_utils_js_1.getAppInfoByProject)(this.projectModel);
        return [...(0, wdk_1.difference)(e, t).map(e => {
            const t = path_1.default.resolve(e, "src", "main", "module.json"),
                s = path_1.default.resolve(e, "src", "main", "module.json5");
            return fs_extra_1.default.existsSync(t) ? t : s
        }), ...t.map(e => path_1.default.resolve(e, "src", "main", "module.json5"))].map(e => {
            var t, i, o;
            let r;
            return r =
                e.endsWith("module.json") ? fs_extra_1.default.readJsonSync(e) : hvigor_1.Json5Reader.getJson5Obj(e), {
                moduleName: r.module.name,
                versionCode: (null === (t = null == r ? void 0 : r.app) || void 0 === t ? void 0 : t.bundleName) &&
                    null !== (o = null === (i = null == r ? void 0 : r.app) || void 0 === i ? void 0 : i.versionCode) &&
                    void 0 !== o ? o : s
            }
        })
    }

    collectHarAbilities(e) {
        const t = [];
        return this.service.getHarDependencies().forEach(s => {
            var i;
            const o = s.getModuleJsonObj();
            if (!o) {
                return;
            }
            const r = null === (i = o.module) || void 0 === i ? void 0 : i[e];
            (null == r ? void 0 : r.length) && r.forEach(e => {
                const i = (0, wdk_1.cloneDeep)(e);
                i.srcEntry && (Object.assign(i, {
                    srcEntry: (0, ohmurl_utils_js_1.generateOhmurlForSrcEntry)(this.targetService, this.moduleName, s,
                        i.srcEntry),
                    moduleName: s.getDependencyName(),
                    arkTSMode: i.arkTSMode === common_const_js_1.ArkTSVersionConst.ARKTS1_2 ?
                    common_const_js_1.ArkTSModeConst.STATIC : common_const_js_1.ArkTSModeConst.DYNAMIC
                }), t.push(i))
            })
        }), t
    }

    addHarAbilitiesToModuleJson(e, t, s) {
        var i;
        s.length && ((i = e.module)[t] || (i[t] = []), e.module[t].push(...s))
    }

    processDependencyHarAbility(e) {
        if (!e || !this.shouldCollectDependenciesAbilities) {
            return;
        }
        const t = this.collectHarAbilities(common_const_js_1.AbilityConst.UI_ABILITY);
        this.addHarAbilitiesToModuleJson(e, common_const_js_1.AbilityConst.UI_ABILITY,
            t), this.addHarAbilitiesToModuleJson(e, common_const_js_1.AbilityConst.EXTENSION_ABILITY,
            this.harExtensionAbilities), this.checkDuplicateAbility(e.module[common_const_js_1.AbilityConst.UI_ABILITY])
    }

    findDuplicatedAbilityNames(e) {
        if (!(null == e ? void 0 : e.length)) {
            return [];
        }
        const t = new Map;
        return e.forEach(e => {
            var s, i;
            const o = null !== (s = e.moduleName) && void 0 !== s ? s : this.moduleName;
            t.has(e.name) ? null === (i = t.get(e.name)) || void 0 === i || i.push(o) :
            t.set(e.name, [o]), e.moduleName && delete e.moduleName
        }), Array.from(t.entries()).filter(([e, t]) => t.length > 1)
    }

    checkDuplicateAbility(e) {
        if (!(null == e ? void 0 : e.length)) {
            return;
        }
        const t = this.findDuplicatedAbilityNames(e);
        0 !== t.length &&
        _log.printErrorExit("DUPLICATE_MODULE_ABLITIES_OBJECT_NAMES_DETECTED", void 0, [[JSON.stringify([...t])]])
    }

    addModuleDependencies(e) {
        this.moduleModel.isHarModule() && !0 ===
        hvigor_1.hvigorCore.getParameter().getProperty(common_const_js_1.CommonConst.HAR_EXCLUDE_HSP_DEPENDENCIES) ||
            (e.module.dependencies = this._dependencies)
    }

    processModuleAndAbility(e) {
        var t, s;
        if (e.module) {
            let t = common_const_js_1.ArkTSModeConst.DYNAMIC;
            if (this.targetService.verifyModuleVersionIsArkTS12()) {
                t = common_const_js_1.ArkTSModeConst.STATIC;
                const s = e.module.srcEntry;
                s && (e.module.srcEntry =
                    (0, ohmurl_utils_js_1.generateOhmUrlV2ForSrcEntry)(this.targetService.getPkgContextInfo(this.packageJsonObj.name),
                        s))
            }
            e.module.moduleArkTSMode = t;
            e.module.arkTSMode = t;
        }
        null === (s = null === (t = e.module) || void 0 === t ? void 0 : t.abilities) || void 0 === s ||
        s.forEach(e => {
            var t;
            this.targetService.verifyModuleVersionIsArkTS12() && !e.arkTSMode && (e.arkTSMode =
                null !== (t = e.arkTSMode) && void 0 !== t ? t : common_const_js_1.ArkTSModeConst.STATIC, e.srcEntry =
                (0, ohmurl_utils_js_1.generateOhmUrlV2ForSrcEntry)(this.targetService.getPkgContextInfo(this.packageJsonObj.name),
                    e.srcEntry))
        })
    }

    processExtensionAbility(e) {
        var t, s;
        null === (s = null === (t = null == e ? void 0 : e.module) || void 0 === t ? void 0 : t.extensionAbilities) ||
            void 0 === s || s.forEach(e => {
            var t;
            this.targetService.getSelfArkTSVersion() === common_const_js_1.ArkTSVersionConst.ARKTS1_2 &&
                (e.arkTSMode = common_const_js_1.ArkTSModeConst.STATIC, e.srcEntry =
                    (0, ohmurl_utils_js_1.generateOhmUrlV2ForSrcEntry)(this.targetService.getPkgContextInfo(this.packageJsonObj.name),
                        e.srcEntry)), e.arkTSMode =
                null !== (t = e.arkTSMode) && void 0 !== t ? t : common_const_js_1.ArkTSModeConst.DYNAMIC
        })
    }

    processTestRunner(e) {

        const modulePath = this.service.getModuleModel().getModule().getNodeDir();
        const path = require('path');
        const fs = require('fs');
        const oldTestRunner = path.resolve(modulePath,'src/main/src/testrunner/OpenHarmonyTestRunner.ets');
        if (fs.existsSync(oldTestRunner) && this.targetService.verifyModuleVersionIsArkTS12()) {
            const testRunner = {
                "arkTSMode": "static",
                "name": "test",
                "srcPath": "entry/src/main/src/testrunner/OpenHarmonyTestRunner"
            }
            e.module.testRunner = testRunner;
            return;
        }

        var t, s;
        const i = null === (s = null === (t = null == e ? void 0 : e.module) || void 0 === t ? void 0 : t.testRunner) ||
            void 0 === s ? void 0 : s.srcPath;
        i && this.targetService.verifyModuleVersionIsArkTS12() && (e.module.testRunner.srcPath =
            (0, ohmurl_utils_js_1.generateOhmUrlV2ForSrcEntry)(this.targetService.getPkgContextInfo(this.packageJsonObj.name),
                i, "src/ohosTest", !0), e.module.testRunner.arkTSMode = common_const_js_1.ArkTSModeConst.STATIC)
    }
}

exports.ProcessProfile = ProcessProfile;
